package com.xcx.minservice.untils;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class MinioUtil {

    private String bucketName = "xcx";
    @Resource
    private MinioClient minioClient;

    @Value("${image.header}")
    private String imageHeader;


    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            //e.printStackTrace();
            return false;
        }
        return found;
    }


    /**
     * 创建存储bucket
     *
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 删除存储bucket
     *
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    @SneakyThrows(Exception.class)
    public String upload(MultipartFile file) {

        //判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return "文件内容不能为空";
        }
        String type = VerifyFileType.getFileTypeBySuffix(file);
        String fileName = file.getOriginalFilename();
        String newName = null;
        String contentType = file.getContentType();
        log.info("获取到的文件类型：{}", contentType);
        if ("image".equals(type)) {
            //图片
            newName = "img/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
        } else if ("audio".equals(type)) {
            newName = "audio/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
        } else if ("video".equals(type)) {
            newName = "video/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
        } else if ("doc".equals(type)) {
            if ("multipart/form-data".equals(contentType)) {
                contentType = "application/msword";
            }
            newName = "doc/" + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
        } else {
            return "该文件类型不能上传！";
        }
        InputStream inputStream = file.getInputStream();
//            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(newName)
//                    .stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build();
        //makeBucket(bucketName);
        log.info("更目录:" + bucketName);
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(newName).stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build());
        // minioClient.putObject(bucketName, newName, inputStream, contentType);
        inputStream.close();
        //文件名称相同会覆盖
//            minioClient.putObject(objectArgs);
        String url = imageHeader + newName;
        return url;
    }

    @SneakyThrows(Exception.class)
    public List<String> uploads(MultipartFile[] files) {
        List<String> fileNameList = new ArrayList<>(files.length);

        for (MultipartFile file: files
             ) {
            String type = VerifyFileType.getFileTypeBySuffix(file);
            String fileName = file.getOriginalFilename();
            String newName = null;
            String contentType = file.getContentType();
            log.info("获取到的文件类型：{}", contentType);
            if ("image".equals(type)) {
                //图片
                newName = "img/" + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
            } else if ("audio".equals(type)) {
                newName = "audio/" + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
            } else if ("video".equals(type)) {
                newName = "video/" + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
            } else if ("doc".equals(type)) {
                if ("multipart/form-data".equals(contentType)) {
                    contentType = "application/msword";
                }
                newName = "doc/" + UUID.randomUUID().toString().replaceAll("-", "")
                        + fileName.substring(fileName.lastIndexOf("."));
            } else {
                fileNameList.add("该文件类型不能上传！");

            }
            InputStream inputStream = file.getInputStream();
//            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(newName)
//                    .stream(file.getInputStream(),file.getSize(),-1).contentType(file.getContentType()).build();
            //makeBucket(bucketName);
            log.info("更目录:" + bucketName);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(newName).stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build());
            // minioClient.putObject(bucketName, newName, inputStream, contentType);
            inputStream.close();
            String url = imageHeader + newName;
            fileNameList.add(url);
        }
        //文件名称相同会覆盖
//            minioClient.putObject(objectArgs);

        return fileNameList;
    }


















    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    public String preview(String fileName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
//        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
//                .object(fileName).build();
//        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
//            byte[] buf = new byte[1024];
//            int len;
//            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
//                while ((len=response.read(buf))!=-1){
//                    os.write(buf,0,len);
//                }
//                os.flush();
//                byte[] bytes = os.toByteArray();
//                res.setCharacterEncoding("utf-8");
//                //设置强制下载不打开
//                //res.setContentType("application/force-download");
//                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//                try (ServletOutputStream stream = res.getOutputStream()){
//                    stream.write(bytes);
//                    stream.flush();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        InputStream in = null;
        try {
            StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
            res.setContentType(stat.contentType());
            //是否需要
            res.setCharacterEncoding("utf-8");
            res.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            IOUtils.copy(in, res.getOutputStream());
        } catch (Exception e) {
            log.info(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.info(e.getMessage());
                }
            }
        }


    }

    /**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }













}
